package com.anjiplus.template.gaea.auth.modules.websocket;

import com.alibaba.fastjson.JSON;
import com.anji.plus.gaea.constant.GaeaConstant;
import com.anji.plus.gaea.utils.GaeaUtils;
import com.anjiplus.template.gaea.auth.modules.websocket.dto.CommonMsgDto;
import com.anjiplus.template.gaea.auth.modules.websocket.dto.UserMsgDto;
import com.anjiplus.template.gaea.common.config.GaeaRedisClient;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.simp.SimpMessageSendingOperations;
import org.springframework.messaging.simp.user.SimpUser;
import org.springframework.messaging.simp.user.SimpUserRegistry;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * 功能描述：
 * websocket发送信息入口
 * @Author: peiyanni
 * @Date: 2021/4/2 14:37
 */
@Service
@Slf4j
public class WebSocketService {

    private static final String HANDLER_NAME = "socketHandler";

    @Resource
    private GaeaRedisClient gaeaRedisClient;
    @Autowired
    private SimpMessageSendingOperations simpMessageSendingOperations;

    @Autowired
    private SimpUserRegistry simpUserRegistry;

    /**
     * 服务端推送消息--一对一
     * 单体服务
     * 客服端 订阅地址为/users/{username}/message
     *
     * @param username
     */
    public void pushMessage(String username, GaeaWsMessage gaeaWsMessage) {
        try {
            SimpUser simpUser = simpUserRegistry.getUser(username);
            if (null == simpUser) {
                return;
            }
            log.info("--服务端指定用户发送消息，to【{}】", simpUser.getName());
            simpMessageSendingOperations.convertAndSendToUser(username, "/message", gaeaWsMessage);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 服务器端推送消息--广播
     * 客服端 订阅地址为/topic/message
     * 单体服务
     */
    public void pushMessage(GaeaWsMessage gaeaWsMessage) {
        try {
            String nowTime = GaeaUtils.formatDate(new Date(), GaeaConstant.TIME_PATTERN);
            simpMessageSendingOperations.convertAndSend("/topic/message", gaeaWsMessage);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 后台发送消息到redis
     *
     * @param commonMsgDto
     */
    public void sendMessage(CommonMsgDto commonMsgDto) {
        log.info("【websocket消息】广播消息:" + JSON.toJSONString(commonMsgDto));
        Map<String, String> msgMap = new HashMap<>();
        msgMap.put("message", commonMsgDto.getMessage());
        msgMap.put("id", commonMsgDto.getId());
        msgMap.put("eventType",commonMsgDto.getEventType().getValue());
        if(StringUtils.isNotBlank(commonMsgDto.getEventData())){
            msgMap.put("eventData",commonMsgDto.getEventData());
        }
        gaeaRedisClient.sendMessage(HANDLER_NAME, msgMap);
    }

    /**
     * 此为单点消息--发送到redis
     *
     * @param userMsgDto
     */
    public void sendMessage(UserMsgDto userMsgDto) {
        Map<String, String> msgMap = new HashMap<>();
        msgMap.put("username", userMsgDto.getUsername());
        msgMap.put("message", userMsgDto.getMessage());
        msgMap.put("id", userMsgDto.getId());
        msgMap.put("eventType",userMsgDto.getEventType().getValue());
        if(StringUtils.isNotBlank(userMsgDto.getEventData())){
            msgMap.put("eventData",userMsgDto.getEventData());
        }
        gaeaRedisClient.sendMessage(HANDLER_NAME, msgMap);
    }

    /**
     * 此为单点消息(多人)
     *
     * @param userMsgDtos
     */
    public void sendMessage(List<UserMsgDto> userMsgDtos) {
        if(CollectionUtils.isEmpty(userMsgDtos)){
            return;
        }
        for (UserMsgDto userMsgDto : userMsgDtos) {
            sendMessage(userMsgDto);
        }
    }

}